package com.cskaoyan.controller.wx;

import com.cskaoyan.bean.BaseRespVo;
import com.cskaoyan.bean.bo.WxAuthRegCaptchaBO;
import com.cskaoyan.bean.bo.WxRegisterBO;


import com.cskaoyan.service.WxAuthService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.Serializable;

/**
 * 创建日期: 2022/04/12 09:54
 *
 * @author HanWeiqi
 */
@RequestMapping("wx/auth")
@RestController
public class WxAuthController {
    @Autowired
    WxAuthService wxAuthService;

    // 获取验证码
    @PostMapping("regCaptcha")
    public BaseRespVo regCaptcha(@RequestBody WxAuthRegCaptchaBO wxAuthRegCaptchaBO, HttpServletRequest request) {
        String code = wxAuthService.regCaptcha(wxAuthRegCaptchaBO.getMobile());
        Session session = SecurityUtils.getSubject().getSession();
        Serializable id = session.getId();
        session.setAttribute("code",code);
        return BaseRespVo.ok(id);
    }

    // 注册
    @PostMapping("register")
    public BaseRespVo register(@RequestBody WxRegisterBO wxRegisterBO){
        Session session = SecurityUtils.getSubject().getSession();
        String code = (String) session.getAttribute("code");
        if(wxRegisterBO.getCode().equals(code)){
            int count = wxAuthService.register(wxRegisterBO);
            if(count == 1){
                return BaseRespVo.ok(wxRegisterBO.getUsername());
            }else if(count == 404){
                return BaseRespVo.fail(703,"该用户已存在");
            }else{
                return BaseRespVo.fail(500,"系统异常");
            }
        }else{
            return BaseRespVo.fail(703,"验证码错误");
        }

    }
}
